const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults({
    bodyParser: true,
})

server.use(middlewares)

// 给req挂载db
server.use((req, res, next) => {
    req.db = router.db
    next()
})

const { login, chat } = require('./routers')
const { getToken } = require('./utils/token')

// 登录
server.post('/login', login)

// 如果是添加用户请求，则需要验证邮箱的唯一性
server.post('/users', (req, res, next) => {
    const { db } = req
    const { email } = req.body
    // 从数据库中查询用户是否存在
    const user = db.get('users').find({ email }).value()
    if (user) {
        res.send({
            success: false,
            msg: '邮箱已经被注册',
        })
    } else {
        req.headers.authorization = getToken({ id: 0, date: Date.now() })
        next()
    }
})

// 验证token
server.use(require('./middlewares/auth'))

// 获取当前登录用户信息
server.get('/user', (req, res) => {
    const { id } = req
    let user = { ...req.db.get('users').find({ id }).value() }
    delete user.password
    res.send({
        success: true,
        msg: '获取用户信息成功',
        data: user,
    })
})

// 提问
server.post('/chat', chat)

router.render = (req, res) => {
    // 删除password
    if (req.path.startsWith('/users')) {
        // 判断res.locals.data是平面对象还是数组
        if (Array.isArray(res.locals.data)) {
            res.locals.data.forEach((item) => {
                delete item.password
            })
        } else if (res.locals.data) {
            delete res.locals.data.password
        }
    }

    // 判断请求是否成功
    const success = res.statusCode < 400

    res.json({
        success,
        data: res.locals.data,
        msg: success ? '请求成功' : '请求失败',
    })
}

server.use(router)

server.listen(3000, () => {
    console.log('JSON Server is running')
})
